package com.lbd.system.controller;

import com.lbd.commons.Result;
import com.lbd.commons.ResultState;
import com.lbd.system.bean.Employee;
import com.lbd.system.controller.vo.HomeVo;
import com.lbd.system.service.HomeService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 描述：
 * 创建时间2016/12/26 13:14
 * 创建人 yangzhuo
 */
@RestController
@RequestMapping("/home")
public class HomeController {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private HomeService homeService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(HttpServletRequest request, HttpServletResponse response) throws ParseException {

        //获取系统信息
        HomeVo homeVo = homeService.find(getDateStart());

        Employee employee = (Employee) request.getSession().getAttribute(Employee.SESSION_USER);
        try {
            BeanUtils.copyProperties(homeVo, employee);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.info("查看首页信息时属性copy个人信息出现异常：");
            log.info(e);
        }

        //借款管理
        Map loan = homeService.findLoanInfo();
        if (loan != null) {
            homeVo.setWclLoanNum(this.objectToInteger(loan.get("wclLoanNum")));
            homeVo.setReviewTargetNum(this.objectToInteger(loan.get("reviewTargetNum")));
        }

        //获取平台运营总数据
        Map total = homeService.findInvestment(null, null);
        if (total != null) {
            homeVo.setTotalInvest(this.objectToBigDecimal(total.get("invest")));
            homeVo.setTotalUser(this.objectToInteger(total.get("user")));
            homeVo.setTotalReturn((BigDecimal) total.get("return"));
            homeVo.setTotalTargetNum(this.objectToInteger(total.get("targetNum")));
        }

        //获取昨日统计平台运营总数据
        Map yesterday = homeService.findInvestment(DateUtils.addDays(getDateStart(), -1), getDateStart());
        if (yesterday != null) {
            homeVo.setYesInvest(this.objectToBigDecimal(yesterday.get("invest")));
            homeVo.setYesAddUser(this.objectToInteger(yesterday.get("user")));
            homeVo.setYesReturn((BigDecimal) yesterday.get("return"));
            homeVo.setYesLoanTarget(this.objectToInteger(yesterday.get("targetNum")));

        }

        //获取上周平台运营总数据
        Map lastWeek = homeService.findInvestment(getDateLastWeekBegin(), DateUtils.addDays(getDateLastWeekBegin(), 7));
        if (lastWeek != null) {
            homeVo.setLastWeekInvest(this.objectToBigDecimal(lastWeek.get("invest")));
            homeVo.setLastWeekAddUser(this.objectToInteger(lastWeek.get("user")));
            homeVo.setLastWeekReturn((BigDecimal) lastWeek.get("return"));
            homeVo.setLastWeekLoanTarget(this.objectToInteger(lastWeek.get("targetNum")));
        }

        return new Result(ResultState.SUCCESS, "查询成功", homeVo);
    }

    /**
     * 将Object 转化成 BigDecimal
     *
     * @param value
     * @return
     */
    private BigDecimal objectToBigDecimal(Object value) {
        if (value != null) {
            return BigDecimal.valueOf((double) value);
        } else {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 将Object 转化成 Integer
     *
     * @param value
     * @return
     */
    private Integer objectToInteger(Object value) {
        if (value != null) {
            return Integer.valueOf(value.toString());
        } else {
            return 0;
        }
    }

    /**
     * 获取当天的开始时间（0点0分0秒）
     *
     * @return
     */
    private Date getDateStart() {
        return getDateStart(new Date());
    }

    /**
     * 获取日期对应的开始时间（0点0分0秒）
     *
     * @param date
     * @return
     */
    private Date getDateStart(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date start = calendar.getTime();
        return start;
    }

    /**
     * 获取上一周开始时间（周一0点0分0秒）
     *
     * @return
     */
    private Date getDateLastWeekBegin() {
        return getDateLastWeekBegin(new Date());
    }

    /**
     * 获取上一周的开始时间（周一0点0分0秒）
     *
     * @param date
     * @return
     */
    private Date getDateLastWeekBegin(Date date) {
        Calendar cal = Calendar.getInstance();
        //n为推迟的周数，1本周，-1向前推迟一周，2下周，依次类推
        int n = 1;
        cal.add(Calendar.DATE, -n * 7);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return getDateStart(cal.getTime());
    }

}
